package com.example.airoles.service;

import com.example.airoles.dto.ConversationSession;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Service
public class ConversationSessionService {
    
    private final Map<String, ConversationSession> activeSessions = new ConcurrentHashMap<>();
    private final Map<String, List<ConversationSession>> userSessions = new ConcurrentHashMap<>();
    
    public ConversationSession createSession(String userId, String roleId, String skill) {
        ConversationSession session = new ConversationSession(userId, roleId, skill);
        activeSessions.put(session.sessionId, session);
        
        userSessions.computeIfAbsent(userId, k -> new ArrayList<>()).add(session);
        
        return session;
    }
    
    public ConversationSession getSession(String sessionId) {
        return activeSessions.get(sessionId);
    }
    
    public ConversationSession getOrCreateSession(String sessionId, String userId, String roleId, String skill) {
        if (sessionId != null && activeSessions.containsKey(sessionId)) {
            ConversationSession session = activeSessions.get(sessionId);
            session.lastActiveAt = LocalDateTime.now();
            return session;
        }
        return createSession(userId, roleId, skill);
    }
    
    public List<ConversationSession> getUserSessions(String userId) {
        return userSessions.getOrDefault(userId, new ArrayList<>());
    }
    
    public List<ConversationSession> getRecentSessions(String userId, int limit) {
        return getUserSessions(userId).stream()
                .sorted((a, b) -> b.lastActiveAt.compareTo(a.lastActiveAt))
                .limit(limit)
                .collect(Collectors.toList());
    }
    
    public void updateSessionActivity(String sessionId) {
        ConversationSession session = activeSessions.get(sessionId);
        if (session != null) {
            session.lastActiveAt = LocalDateTime.now();
        }
    }
    
    public void cleanupInactiveSessions() {
        LocalDateTime cutoff = LocalDateTime.now().minusHours(24);
        activeSessions.entrySet().removeIf(entry -> 
            entry.getValue().lastActiveAt.isBefore(cutoff));
    }
    
    public ConversationSession.ConversationContext getSessionContext(String sessionId) {
        ConversationSession session = activeSessions.get(sessionId);
        return session != null ? session.context : null;
    }
    
    public void updateSessionContext(String sessionId, String key, Object value) {
        ConversationSession session = activeSessions.get(sessionId);
        if (session != null) {
            session.updateContext(key, value);
        }
    }
}